<?php

namespace app\admin\controller\exchange;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 提货码信息
 *
 * @icon fa fa-circle-o
 */
class Code extends Backend
{

    /**
     * Code模型对象
     * @var \app\admin\model\exchange\Code
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exchange\Code;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //提货码的状态
        $statusList = $this->model->field('count(*) as count,status')
        ->group('status')
        ->select();
        $unActivate = 0;
        $activated = 0;
        $used = 0;
        foreach ($statusList as $k=>$value){
            if ($value->status == 0){
                $unActivate = $value->count;
            }
            if ( $value->status == 1){
                $activated = $value->count;
            }

            if ($value->status === 2){
                $used = $value->count;
            }
        }
        $statusRes['unActivate'] = $unActivate;
        $statusRes['activated'] = $activated;
        $statusRes['used'] = $used;


        //print_r($unActivate.$activated.$used);

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['library'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','code','status','end_time','order_id','user_id','mobile']);
                $row->visible(['library']);
				$row->getRelation('library')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items(),"statusRes"=>$statusRes);

            return json($result);
        }
        $this->view->assign("statusRes", $statusRes);

        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($params['num'] < 1) {
            $this->error(__('生成数量至少1个', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $count = 0;
        Db::startTrans();
        try {
            for ($i=0; $i < (int)$params['num']; $i++) { 
                $data = array(
                    'library_id' => $params['library_id'],
                    'code' => $this->english_num(),
                    'status' => 0,
                );
                $count += $this->model->insert($data);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were inserted'));
    }

    private function english_num()
    {
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $temp = '';
        while (strlen($temp) < 19) {
            $index = mt_rand(0, strlen($s) - 1);
            $temp .= $s[$index];
            if (strlen($temp) == 4 || strlen($temp) == 9 || strlen($temp) == 14) {
                $temp .= '-';
            }
        }
        // 判断是否重复
        $code = $this->model->where(['code'=> $temp])->find();
        if (empty($code)) {
            return $temp;
        } else {
            return $this->english_num;
        }
        
    }

    /**
     * 查看
     */
    public function goods($ids)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where1 = array('good_id'=>['=',$ids]);
            if (!empty($filter) && !empty($filter['codes'])) {
                $where1['code'] = ['like','%'.$filter['codes'].'%'];
                unset($filter['codes']);
                $this->request->get(['filter'=>json_encode($filter)]);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->with(['library'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row['codes'] = $row['code'];
                $row->visible(['id','code','codes','status','end_time','order_id','user_id','mobile']);
                $row->visible(['library']);
				$row->getRelation('library')->visible(['name']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $this->assignconfig("ids", $ids);
        return $this->view->fetch();
    }
}
